/*
 * @lc app=leetcode.cn id=289 lang=cpp
 *
 * [289] 生命游戏
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution
{
    int cnt(const vector<vector<int>> &board, int x, int y)
    {
        int ans = 0;
        int lr[] = {-1, 1, 0, 0, -1, -1, 1, 1};
        int ud[] = {0, 0, -1, 1, -1, 1, -1, 1};
        for (int i = 0; i < 8; i++)
        {
            int nx = x + lr[i];
            int ny = y + ud[i];
            if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size())
            {
                ans += board[nx][ny];
            }
        }
        return ans;
    }

public:
    void gameOfLife(vector<vector<int>> &board)
    {
        vector<vector<int>> ans(
            board.size(), vector<int>(board[0].size(), 0));
        for (int x = 0; x < board.size(); x++)
        {
            for (int y = 0; y < board[0].size(); y++)
            {
                int tmp = cnt(board, x, y);
                if (tmp < 2 || tmp > 3)
                {
                    ans[x][y] = 0;
                }
                else
                {
                    // tmp == 2 或者 3
                    if (tmp == 3)
                    {
                        ans[x][y] = 1;
                    }
                    else
                    {
                        ans[x][y] = board[x][y];
                    }
                }
            }
        }
        board.swap(ans);
        return;
    }
};
// int main(int argc, char const *argv[])
// {
//     vector<vector<int>> board = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
//     Solution().gameOfLife(board);
//     return 0;
// }

// @lc code=end
